import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import ProductList from '../views/ProductList.vue'
import ProductDetail from '../views/ProductDetail.vue'
import Cart from '../views/Cart.vue'
import Checkout from '../views/Checkout.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import OrderDetail from '../views/OrderDetail.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/category/:category',
    name: 'ProductList',
    component: ProductList,
    props: true
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: ProductDetail,
    props: true
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart
  },
  {
    path: '/checkout',
    name: 'Checkout',
    component: Checkout,
    meta: { requiresAuth: true } // 需要登录
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresGuest: true } // 仅未登录访问
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresGuest: true } // 仅未登录访问
  },
  {
    path: '/order/:id',
    name: 'OrderDetail',
    component: OrderDetail,
    props: true,
    meta: { requiresAuth: true } // 需要登录
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 动态导入，避免循环依赖
  import('../stores/auth').then(({ useAuthStore }) => {
    const authStore = useAuthStore()
    
    // 如果访问需要登录的页面
    if (to.meta.requiresAuth && !authStore.isAuthenticated) {
      // 保存目标路由，登录后跳转
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
    // 如果访问仅限游客的页面（登录/注册）
    else if (to.meta.requiresGuest && authStore.isAuthenticated) {
      // 已登录用户访问登录页，跳转到首页
      next('/')
    }
    else {
      next()
    }
  })
})

export default router

